/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server;
//<editor-fold defaultstate="collapsed" desc=" các thư viện sử dụng">
import java.awt.Component;
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;



//</editor-fold>
/**
 *
 * @author KingofSpeed
 */
public class CreateTableForm extends javax.swing.JFrame {
     //<editor-fold defaultstate="collapsed" desc="Bien toan cuc">
    String name = "";
    MainWindow parent;
    public int type;
    public DefaultTableModel tableModel;
    int cStt = 0;  int cName = 1;  int cType = 2;  int cKey = 3;  int cNotNull = 4;
    JPopupMenu popupMenu;
    List<Column> columns;
    ArrayList<String> columnsToDelete;
    ArrayList<String> columnsToRename;
    int index;
    DataTable newTable;
    //</editor-fold>
     //<editor-fold defaultstate="collapsed" desc="Hàm khởi tạo">
    public CreateTableForm( MainWindow _main, int _type, int _index, String _name ) 
    {
        initComponents();
        columnsToDelete = new ArrayList<String>();
        columnsToRename = new ArrayList<String>();
        columns = new ArrayList<Column>();
            newTable = new DataTable(_main);
            newTable.setName(_name);
        parent = _main;  type = _type;  name = _name;  index = _index;
        tbTableName.setText(_name);
        CreateTable();
        
        CreatePopupMenu();
        if ( _type == 1 )
        {
            LoadTable();
        }
        
        
    }
    //</editor-fold>
     //<editor-fold defaultstate="collapsed" desc=" hàm load các cột có sẵn khi sửa một bảng nào đó">
    public void LoadTable()
    {
        if ( index == -1 )
            return ;
        for ( int i = 0; i < newTable.getnColumn(); i++ )
        {
            Object[] data = {i+1, newTable.getColumns().get(i).getTitle(), "", "", "false"};
            if ( newTable.getColumns().get(i).isIsNotNull() == true )
                data[cNotNull] = "true";
            if ( newTable.getColumns().get(i).isIsHaveForeignKey() 
                    && newTable.getColumns().get(i).isIsPrimary())
                data[cKey] = "p,f";
            else if ( newTable.getColumns().get(i).isIsHaveForeignKey() )
                 data[cKey] = "f";
            else if ( newTable.getColumns().get(i).isIsPrimary())
                data[cKey] = "p";
            else
                data[cKey] = "";
            data[cType] = newTable.getColumns().get(i).getType();
            tableModel.addRow( data);
        }
    }
    //</editor-fold>
     //<editor-fold defaultstate="collapsed" desc="hàm tạo bảng để xem các cột đang có của bảng đang thao tác">
    public void CreateTable()
    {
        if ( type == 1 )
        {
            newTable.setColumns(parent.dataTables.get(index).getColumns());
            newTable.setModel(parent.dataTables.get(index).getModel());
            newTable.setnColumn(parent.dataTables.get(index).getnColumn());
            columns = newTable.getColumns();
        }
         //<editor-fold defaultstate="collapsed" desc="Disable một số thuộc tính không cho sửa trực tiếp giống bên SQL server">
        tableModel = new DefaultTableModel( null , new Object[]{"STT","Name","Type", "Key", "Not Null" })
        {
            @Override
            public boolean isCellEditable(int row, int col)
            {
                 ToolSQL toolSQL = new ToolSQL(parent);
                int n = toolSQL.NameToIndex(name);
                if ( type == 1 && n != -1 )
                {
                    int index = toolSQL.TitleToIndex(n, String.valueOf(tableModel.getValueAt(row, cName)));
                    if ( index != - 1)
                    {
                        int size = parent.dataTables.get(n).getColumns().get(index).getListRow().size();
                        if ( size  > 0 && ( col == cNotNull || col == cType ))
                            return false;
                    }
                }
                if ( col == cStt || col == cKey || col ==  cName )
                    return false;
                return true;
            }
        };
        //</editor-fold>
        tablePreview.addKeyListener(new TableKeyListener());
        tablePreview.setModel(tableModel);
        tablePreview.setRowHeight(35);
        tablePreview.getTableHeader().setReorderingAllowed(false);
        JCheckBox checkBox = new JCheckBox();
        TableCellRenderer render = new JComponentTableCellRenderer();  
        String[] items = new String[]{"Number", "String"};
        tablePreview.getColumnModel().getColumn(cNotNull).setCellEditor(new DefaultCellEditor(checkBox)); 
        tablePreview.getColumnModel().getColumn(cType).setCellEditor(new MyComboboxEditor(items));  
        tablePreview.getColumnModel().getColumn(cType).setCellRenderer(new MyComboboxRenderer(items));  
    }
    //</editor-fold>
     // <editor-fold defaultstate="collapsed" desc="Code generate">
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        bAddColumn = new javax.swing.JButton();
        bForeignKey = new javax.swing.JButton();
        bPrimaryKey = new javax.swing.JButton();
        bDeleteColumn = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablePreview = new javax.swing.JTable();
        bOk = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        tbTableName = new javax.swing.JTextField();
        bRenameColumn = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        bAddColumn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SourceImage/AddColumnNormal.png"))); // NOI18N
        bAddColumn.setToolTipText("Add Columns");
        bAddColumn.setAlignmentY(0.0F);
        bAddColumn.setBorder(null);
        bAddColumn.setBorderPainted(false);
        bAddColumn.setContentAreaFilled(false);
        bAddColumn.setMargin(new java.awt.Insets(0, 0, 0, 0));
        bAddColumn.setMaximumSize(new java.awt.Dimension(75, 75));
        bAddColumn.setMinimumSize(new java.awt.Dimension(50, 50));
        bAddColumn.setPreferredSize(new java.awt.Dimension(60, 60));
        bAddColumn.setVerifyInputWhenFocusTarget(false);
        bAddColumn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                bAddColumnMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                bAddColumnMouseExited(evt);
            }
        });
        bAddColumn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bAddColumnActionPerformed(evt);
            }
        });

        bForeignKey.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SourceImage/KeyForeignNormal.png"))); // NOI18N
        bForeignKey.setToolTipText("Add Foreign Key");
        bForeignKey.setContentAreaFilled(false);
        bForeignKey.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                bForeignKeyMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                bForeignKeyMouseExited(evt);
            }
        });
        bForeignKey.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bForeignKeyActionPerformed(evt);
            }
        });

        bPrimaryKey.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SourceImage/KeyPrimaryNormal.png"))); // NOI18N
        bPrimaryKey.setToolTipText("Add Primary Key");
        bPrimaryKey.setContentAreaFilled(false);
        bPrimaryKey.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                bPrimaryKeyMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                bPrimaryKeyMouseExited(evt);
            }
        });
        bPrimaryKey.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bPrimaryKeyActionPerformed(evt);
            }
        });

        bDeleteColumn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SourceImage/DeleteColumnNormal.png"))); // NOI18N
        bDeleteColumn.setToolTipText("Delete Columns");
        bDeleteColumn.setContentAreaFilled(false);
        bDeleteColumn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                bDeleteColumnMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                bDeleteColumnMouseExited(evt);
            }
        });
        bDeleteColumn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bDeleteColumnActionPerformed(evt);
            }
        });

        tablePreview.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        tablePreview.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        tablePreview.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4", "Title 5"
            }
        ));
        tablePreview.setAlignmentX(1.0F);
        tablePreview.setAlignmentY(1.0F);
        tablePreview.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        tablePreview.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablePreviewMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tablePreview);

        bOk.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SourceImage/OkNormal.png"))); // NOI18N
        bOk.setContentAreaFilled(false);
        bOk.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                bOkMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                bOkMouseExited(evt);
            }
        });
        bOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bOkActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel1.setText("Table Name:");

        tbTableName.setEditable(false);
        tbTableName.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N

        bRenameColumn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SourceImage/RenameNormal.png"))); // NOI18N
        bRenameColumn.setToolTipText("Rename This Column");
        bRenameColumn.setContentAreaFilled(false);
        bRenameColumn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                bRenameColumnMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                bRenameColumnMouseExited(evt);
            }
        });
        bRenameColumn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bRenameColumnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(bAddColumn, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bDeleteColumn, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bPrimaryKey, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bForeignKey, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(tbTableName)))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 377, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(bOk, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bRenameColumn, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(13, 13, 13))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(bAddColumn, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bForeignKey, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bPrimaryKey, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bDeleteColumn, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tbTableName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(bOk, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bRenameColumn, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 225, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed

    }//GEN-LAST:event_formWindowClosed

    private void bAddColumnMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bAddColumnMouseEntered
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/AddColumnClick.png"));
        bAddColumn.setIcon(ii);
    }//GEN-LAST:event_bAddColumnMouseEntered

    private void bAddColumnMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bAddColumnMouseExited
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/AddColumnNormal.png"));
        bAddColumn.setIcon(ii);
    }//GEN-LAST:event_bAddColumnMouseExited

    private void bAddColumnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAddColumnActionPerformed
        AddColumn();
    }//GEN-LAST:event_bAddColumnActionPerformed

    private void bForeignKeyMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bForeignKeyMouseEntered
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/KeyForeignClick.png"));
        bForeignKey.setIcon(ii);
    }//GEN-LAST:event_bForeignKeyMouseEntered

    private void bForeignKeyMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bForeignKeyMouseExited
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/KeyForeignNormal.png"));
        bForeignKey.setIcon(ii);
    }//GEN-LAST:event_bForeignKeyMouseExited

    private void bPrimaryKeyMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bPrimaryKeyMouseEntered
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/KeyPrimaryClick.png"));
        bPrimaryKey.setIcon(ii);
    }//GEN-LAST:event_bPrimaryKeyMouseEntered

    private void bPrimaryKeyMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bPrimaryKeyMouseExited
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/KeyPrimaryNormal.png"));
        bPrimaryKey.setIcon(ii);
    }//GEN-LAST:event_bPrimaryKeyMouseExited

    private void bDeleteColumnMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bDeleteColumnMouseEntered
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/DeleteColumnClick.png"));
        bDeleteColumn.setIcon(ii);
    }//GEN-LAST:event_bDeleteColumnMouseEntered

    private void bDeleteColumnMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bDeleteColumnMouseExited
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/DeleteColumnNormal.png"));
        bDeleteColumn.setIcon(ii);
    }//GEN-LAST:event_bDeleteColumnMouseExited

    private void bDeleteColumnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bDeleteColumnActionPerformed
        RemoveColumn(tablePreview.getSelectedRow());
    }//GEN-LAST:event_bDeleteColumnActionPerformed

    private void bPrimaryKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bPrimaryKeyActionPerformed
        InsertPrimaryKey( tablePreview.getSelectedRow());
    }//GEN-LAST:event_bPrimaryKeyActionPerformed

    private void bForeignKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bForeignKeyActionPerformed
        try
        {
            SaveTableToColumns();
            int r = tablePreview.getSelectedRow();
            if ( r < 0)
                return;
            newTable.setColumns(columns);
            String tableName = name;
            String columnName = (String.valueOf(tableModel.getValueAt(r, cName)));
            String nType = (String.valueOf(tableModel.getValueAt(r, cType)));
            if ( type == 0 )
            {
                parent.dataTables.add(newTable);
                SetForeignKey setforeignkey = new SetForeignKey(this, parent,  tableName, columnName, columns.get(r).getRef(),nType );
                setforeignkey.show();
            }
            else if ( type == 1 )
            {
                SetForeignKey setforeignkey = new SetForeignKey(this, parent,  tableName, columnName, columns.get(r).getRef(), nType);
                setforeignkey.show();
            }
        }
        catch( Exception ex ){}
    }//GEN-LAST:event_bForeignKeyActionPerformed

    private void bOkMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bOkMouseEntered
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/OkClick.png"));
        bOk.setIcon(ii);
    }//GEN-LAST:event_bOkMouseEntered

    private void bOkMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bOkMouseExited
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/OkNormal.png"));
        bOk.setIcon(ii);
    }//GEN-LAST:event_bOkMouseExited

    private void tablePreviewMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablePreviewMouseClicked
        if ( evt.getButton() == MouseEvent.BUTTON3)
        {
            popupMenu.show(tablePreview, evt.getX(), evt.getY());
        }
    }//GEN-LAST:event_tablePreviewMouseClicked

    private void bOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bOkActionPerformed
        if ( Save() == true )
        {
            ShowMessageBox("Lưu Thành Công", "Success");
            parent.LoadTable();
            this.dispose();
        }
        else
            ShowMessageBox("Lưu Thất Bại", "Error");
        
    }//GEN-LAST:event_bOkActionPerformed

    private void bRenameColumnMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bRenameColumnMouseEntered
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/RenameClick.png"));
        bRenameColumn.setIcon(ii);
    }//GEN-LAST:event_bRenameColumnMouseEntered

    private void bRenameColumnMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bRenameColumnMouseExited
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/RenameNormal.png"));
        bRenameColumn.setIcon(ii);
    }//GEN-LAST:event_bRenameColumnMouseExited

    private void bRenameColumnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bRenameColumnActionPerformed
        RenameColumn();
    }//GEN-LAST:event_bRenameColumnActionPerformed
    // </editor-fold>
     //<editor-fold defaultstate="collapsed" desc="lưu lại các thuộc tính của các cột của bảng mà mình đang thao tác">
    public void SaveTableToColumns()
    {
        for ( int i = 0; i < tableModel.getRowCount(); i++ )
        {
            String type = (String.valueOf(tableModel.getValueAt(i, cType)));
            if (type.length() <= 0 )
                type = "String";
            columns.get(i).setType(type);
            if ( String.valueOf(tableModel.getValueAt(i, cType)).equals("true") || columns.get(i).isIsPrimary())
            {
                columns.get(i).setIsNotNull(true);
                tableModel.setValueAt("true", i, cNotNull);
            }
            else
                columns.get(i).setIsNotNull(false);
        }
    }
    //</editor-fold>
     //<editor-fold defaultstate="collapsed" desc=" Lưu bảng vừa tạo ra file xml, nếu trường hợp đang edit bảng thì sẽ gọi hàm riêng">
    public boolean Save()
    {
        SaveTableToColumns();
        if ( type == 0)
        {
            newTable.setColumns(columns);
            parent.dataTables.add(newTable);
            try
            {
                DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = fac.newDocumentBuilder();
                Document doc = builder.newDocument();

                Element root = doc.createElement("Table");
                root.setAttribute("name", name);
                doc.appendChild(root);

                for ( int i = 0;i < columns.size(); i++)
                {
                    Element column = doc.createElement("Column");
                    column.setAttribute("title", columns.get(i).getTitle());
                    if ( columns.get(i).isIsNotNull() == true )
                        column.setAttribute("isNotNull", "Yes");
                    else 
                        column.setAttribute("isNotNull", "No");
                    if ( columns.get(i).isIsPrimary() == true )
                        column.setAttribute("isPrimaryKey", "Yes");
                    else
                        column.setAttribute("isPrimaryKey", "No");
                    if ( columns.get(i).isIsHaveForeignKey() ==  true )
                    {
                        String fkey = "";
                        for ( int j = 0; j< columns.get(i).getRef().size(); j++)
                        {
                            fkey += columns.get(i).getRef().get(j) + ";";
                        }
                        column.setAttribute("foreignKey", fkey);
                    }     
                    else
                        column.setAttribute("foreignKey", "");
                    column.setAttribute("type", columns.get(i).getType());
                    root.appendChild(column);            
                }
                TransformerFactory transfac = TransformerFactory.newInstance();
                Transformer trans = transfac.newTransformer();
                trans.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes");
                trans.setOutputProperty( OutputKeys.INDENT, "yes");

                File file = new File( parent.linkDatabase + "\\" + name + ".xml");
                StreamResult result = new StreamResult(file);
                DOMSource source  = new DOMSource(doc);
                trans.transform(source, result );
                return true;
            }
            catch ( Exception ex ){ return false ;}
        }
        else return ChangeExistTable();
    }
    //</editor-fold>
     //<editor-fold defaultstate="collapsed" desc="Lưu lại các giá trị đã sửa đổi khi sửa bảng, chủ yếu là gọi object khác làm dùm">
    public boolean ChangeExistTable()
    {
        ToolSQL toolSQL = new ToolSQL(parent);
        int index = toolSQL.NameToIndex(name);
        parent.dataTables.get(index).setColumns(columns);
        toolSQL.DeleteColumns(name, columnsToDelete);
        toolSQL.RenameColumns(name, columnsToRename);
        parent.dataTables.get(index).SaveColumnsDeleted(columnsToDelete);
        parent.dataTables.get(index).SaveColumnsRenamed(columnsToRename);
        parent.dataTables.get(index).SaveColumnsChange();
        parent.dataTables.get(index).SaveData();
        parent.LoadTable();
        parent.dsTable.setSelectedIndex(0);
        return true;
    }
    //</editor-fold>
     //<editor-fold defaultstate="collapsed" desc="xử lí khi muốn đổi tên cột">
    public void RenameColumn()
    {
        try
        {
            int index = tablePreview.getSelectedRow();
            if ( index < 0 )
                return ;
            ArrayList<String> tam = new ArrayList<String>();
            for( int i = 0; i < columns.size(); i++)
            {
                if ( i != index )
                    tam.add(columns.get(i).getTitle());
            }
            String colName = String.valueOf(tableModel.getValueAt(index, cName));
            String result = MyJOptionPane.showInputDialog("Nhập vào Tên Cột Mới", "Tên Cột Mới", colName, tam);
            
            if ( result.length() > 0 && !result.equals(colName) )
            {
                columns.get(index).setTitle(result);
                tableModel.setValueAt( result, index , cName);
                if ( type ==  1 )
                    columnsToRename.add(colName + "_" + result);
            }
        }
        catch ( Exception ex ){}
    }
    //</editor-fold>
     //<editor-fold defaultstate="collapsed" desc="xử lí khi muốn set cột đang chọn thành primary key">
    public void  InsertPrimaryKey( int index)
    {
        try
        {
            if ( index < 0 )
                return;
            columns.get(index).setIsPrimary(!columns.get(index).isIsPrimary());
            int r = tablePreview.getSelectedRow();  
            if ( columns.get(index).isIsPrimary())
                tableModel.setValueAt("true", r, cNotNull);
            if ( tableModel.getRowCount() > 0 && r >=0 )
            {
               if ( tableModel.getValueAt(r, cKey).equals(""))
                {
                    tableModel.setValueAt("p", r, cKey);
                }
                else if ( tableModel.getValueAt(r, cKey).equals("p,f"))
                {
                    tableModel.setValueAt("f", r, cKey);
                }
                else if ( tableModel.getValueAt(r, cKey).equals("p"))
                {
                    tableModel.setValueAt("", r, cKey);
                }
                else if ( tableModel.getValueAt(r, cKey).equals("f"))
                {
                    tableModel.setValueAt("p,f", r, cKey);
                }
            }
        }
        catch ( Exception ex ){}
    }
    //</editor-fold>
     //<editor-fold defaultstate="collapsed" desc="Xử lí khi muốn thêm một cột">
    public void AddColumn( )
    {
        try
        {
            ArrayList<String> tam = new ArrayList<String>();
            for( int i = 0; i < columns.size(); i++)
                tam.add(columns.get(i).getTitle());
            String result = MyJOptionPane.showInputDialog("Nhập vào Tên Cột Mới", "Tên Cột", "", tam);
            Column c = new Column();
            if ( result.length() > 0 )
            {
                c.setTitle(result);
                if ( tableModel.getRowCount() == 0 )
                {
                    if ( type == 1 )
                        tableModel.addRow( new Object[]{String.valueOf(tableModel.getRowCount() + 1),result , "String", "", "true"});
                    else
                        tableModel.addRow( new Object[]{String.valueOf(tableModel.getRowCount()+ 1),result , "", "", "false"});
                }
                else
                {
                    if ( type == 1 )
                        tableModel.addRow( new Object[]{String.valueOf(tableModel.getRowCount() + 1),result , "String", "", "true"});
                    else
                        tableModel.addRow( new Object[]{String.valueOf(tableModel.getRowCount()+ 1),result , "String", "", "false"});
                }
                columns.add(c);
            }
            
        }
        catch ( Exception e ){}
    }
    //</editor-fold>
     //<editor-fold defaultstate="collapsed" desc="Xử lí khi muốn xóa một cột">
    public void RemoveColumn( int index )
    {
        try
        {
            if ( index <  0)
                return;
            if ( type == 1 )
            {
                if( JOptionPane.showConfirmDialog(null, "Xóa Cột Này Sẽ Xóa Tất Cả Các Khóa Ngoại Trỏ Tới Nó, Bạn Có Đồng Ý Không ?"
                        , "Xóa Cột", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION)
                    return ;
                else columnsToDelete.add(String.valueOf(tableModel.getValueAt(index, cName)));
            }
            columns.remove(index);
            tableModel.removeRow(index);
        }
        catch ( Exception ex ){}
    }
    //</editor-fold>
     //<editor-fold defaultstate="collapsed" desc="Đổi tên cột ra số thứ tự của cột trong list">
    public int NameToNumber( String name )
    {
         for ( int i = 0; i < newTable.getListColumn().size(); i++ )
        {
            if ( newTable.getListColumn().get(i).getTitle().equals(name))
                return i;
        }
        return -1;
    }
    //</editor-fold>

    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JButton bAddColumn;
    public javax.swing.JButton bDeleteColumn;
    public javax.swing.JButton bForeignKey;
    public javax.swing.JButton bOk;
    public javax.swing.JButton bPrimaryKey;
    public javax.swing.JButton bRenameColumn;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    public javax.swing.JTable tablePreview;
    public javax.swing.JTextField tbTableName;
    // End of variables declaration//GEN-END:variables
    //<editor-fold defaultstate="collapsed" desc="Class để thêm hình vào cell">
    public class JComponentTableCellRenderer extends DefaultTableCellRenderer
    {
        public JComponentTableCellRenderer()
        {
            super();
        }
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
        {
            JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if ( value instanceof Icon )
             {
                   label.setText(null);
                   label.setIcon((Icon)value);
             }
            return label;
        }
       
    }
    //</editor-fold>
    //<editor-fold defaultstate="collapsed" desc="class để thêm check box vào cell">
    public class CheckBoxTableCellRenderer extends DefaultTableCellRenderer
    {
        public CheckBoxTableCellRenderer()
        {
            super();
        }
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
        {
            JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if ( value instanceof Icon )
             {
                   label.setText(null);
                   label.setIcon((Icon)value);
             }
            return label;
        }
       
    }
    //</editor-fold>
    //<editor-fold defaultstate="collapsed" desc="class tạo combobox chọn type">
    public class MyComboboxEditor extends DefaultCellEditor
    {
        public MyComboboxEditor( String[] items )
        {
            super(new JComboBox(items));
        }
    }
    //</editor-fold>
    //<editor-fold defaultstate="collapsed" desc="Đảm bảo combobox luôn hiện">
    public class MyComboboxRenderer extends JComboBox implements TableCellRenderer
    {
        public MyComboboxRenderer( String []items)
        {
            super(items);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                setSelectedItem(value);
                return this;
        }
        
    }
    //</editor-fold>
    //<editor-fold defaultstate="collapsed" desc="Xử lí Sự kiện gõ phím ">
    class TableKeyListener extends KeyAdapter
    {
       @Override
       public void keyPressed( KeyEvent e )
       {
           if ( e.getKeyCode() == KeyEvent.VK_ENTER )
           {
               try
               {
                   AddColumn();
               }
               catch ( Exception ex ){}
           }
           if ( e.getKeyCode() == KeyEvent.VK_DELETE )
           {
               try
               {
                   RemoveColumn( tablePreview.getSelectedRow());
               }
               catch ( Exception ex ){}
           }
       }
    }
    //</editor-fold>
    //<editor-fold defaultstate="collapsed" desc="hàm xuất ra các bảng thông báo">
     public void ShowMessageBox ( String ms , String l )
    {
        if ( "Error".equals(l))
             JOptionPane.showMessageDialog( this, ms, "Lỗi", JOptionPane.ERROR_MESSAGE);
        else if ( "Success".equals(l))
            JOptionPane.showMessageDialog( this, ms, "Thành Công", JOptionPane.INFORMATION_MESSAGE);
        else
            JOptionPane.showMessageDialog( this, ms, "Thông Báo", JOptionPane.PLAIN_MESSAGE);
    }
     //</editor-fold>
    //<editor-fold defaultstate="collapsed" desc=" Hàm tạo popup menu cho chuột phải">
     public void CreatePopupMenu()
     {
         JMenuItem item;
         popupMenu = new JPopupMenu();
         
         item = new JMenuItem("Insert New Column");
         item.addActionListener( new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                AddColumn();
            }
        });
        
         popupMenu.add(item);
         item = new JMenuItem("Delete Selected Column");
         item.addActionListener( new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                 try
                {
                    if ( tableModel.getRowCount() > 0 && tablePreview.getSelectedColumn() >= 0 )
                        RemoveColumn(tablePreview.getSelectedColumn());
                }
                catch ( Exception ex ){}
            }
        });
         popupMenu.add(item);
         item = new JMenuItem("Set This Column To Primary Key");
         item.addActionListener( new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                InsertPrimaryKey(tablePreview.getSelectedRow());
            }
        }); 
         popupMenu.add(item);
     }
     //</editor-fold>
    //<editor-fold defaultstate="collapsed" desc="Lưu lại những thay đổi của khóa ngoại">
    public void SaveForeignKey(String columnName, ArrayList<String> fkey)
    {
        SaveTableToColumns();
        int index = -1;
        for ( int i = 0; i < columns.size(); i++ )
        {
            if( columns.get(i).getTitle().equals(columnName))
            {
                index = i;
                break;
            }
        }
        if ( index  == -1 )
            return;
        columns.get(index).setRef(fkey);
        try
        {
            if ( columns.get(index).isIsHaveForeignKey() == true )
            {
                if ( tableModel.getValueAt(index, cKey).equals(""))
                    {
                        tableModel.setValueAt("f", index, cKey);
                    }
                else if ( tableModel.getValueAt(index, cKey).equals("p"))
                {
                    tableModel.setValueAt("p,f", index, cKey);
                }
            }
            else if ( columns.get(index).isIsHaveForeignKey() == false )
            {
                if ( tableModel.getValueAt(index, cKey).equals("f"))
                    {
                        tableModel.setValueAt("", index, cKey);
                    }
                else if ( tableModel.getValueAt(index, cKey).equals("p,f"))
                {
                    tableModel.setValueAt("p", index, cKey);
                }
            }
        }
        catch ( Exception ex ){}
    }
    //</editor-fold>
    //<editor-fold defaultstate="collapsed" desc=" getter setter">
    public DataTable getNewTable() {
        return newTable;
    }

    public void setNewTable(DataTable newTable) {
        this.newTable = newTable;
    }
    //</editor-fold>
}